/**
 * 一些通用方法
 */
(function(exports) {

    /**
     * 将string字符串转为html对象,默认创一个div填充
     * 因为很常用，所以单独提取出来了
     * @param {String} strHtml 目标字符串
     * @return {HTMLElement} 返回处理好后的html对象,如果字符串非法,返回null
     */
    exports.parseHtml = function(strHtml) {
        if (typeof strHtml !== 'string') {
            return strHtml;
        }
        // 创一个灵活的div
        var i,
            a = document.createElement('div');
        var b = document.createDocumentFragment();

        a.innerHTML = strHtml;

        while ((i = a.firstChild)) {
            b.appendChild(i);
        }

        return b;
    };

    /**
     * 将对象渲染到模板
     * @param {String} template 对应的目标
     * @param {Object} obj 目标对象
     * @return {String} 渲染后的模板
     */
    exports.renderTemplate = function(template, obj) {
        return template.replace(/[{]{2}([^}]+)[}]{2}/g, function($0, $1) {
            return obj[$1] || '';
        });
    };

    /**
     * 定义一个计数器
     */
    var counterArr = [0];

    /**
     * 添加测试数据
     * @param {String} dom 目标dom
     * @param {Number} count 需要添加的数量
     * @param {Boolean} isReset 是否需要重置，下拉刷新的时候需要
     * @param {Number} index 属于哪一个刷新
     */
    exports.appendTestData = function(dom, count, isReset, index) {
        if (typeof dom === 'string') {
            dom = document.querySelector(dom);
        }

        var prevTitle = typeof index !== 'undefined' ? ('Tab' + index) : '';

        var counterIndex = index || 0;

        counterArr[counterIndex] = counterArr[counterIndex] || 0;

        if (isReset) {
            dom.innerHTML = '';
            counterArr[counterIndex] = 0;
        }

        var template = '<li class="list-item"><h3 class="msg-title">{{title}}</h3><span class="msg-fs14 msg-date">{{date}}</span></li>';

        var template2 = '                                        <li class="J_FavListItem fav-shop clearfix" data-sid = {{brandId}}>\n' +
            '                                            <div class="shop-card g-sl-l-item clcearfix">\n' +
            '                                                <div class="shop-card-side">\n' +
            '                                                    <div class="logo J_ShopClassTri">\n' +
            '                                                        <a target="_blank">\n' +
            '                                                            <img class="logo-img" src="/static/img/seller/shop/{{shopHead}}">\n' +
            '                                                        </a>\n' +
            '                                                    </div>\n' +
            '                                                </div>\n' +
            '                                                <div class="shop-card-main">\n' +
            '                                                    <div class="shop-name">\n' +
            '                                                        <a class="shop-name-link" title="{{shopName}}" target="_blank" href="/shop/view_shop.htm?brandId={{brandId}}">\n' +
            '                                                            {{shopName}}\n' +
            '                                                        </a>\n' +
            '                                                    </div>\n' +
            '                                                    <div class="seller J_ShopClassTri">\n' +
            '                                                        <a class="seller-link" title="tb608980646" target="_blank" href="/shop/view_shop.htm?brandId={{brandId}}">\n' +
            '                                                            {{sellerName}}\n' +
            '                                                        </a>\n' +
            '                                                        <span class="ww-light ww-small">\n' +
            '                                                            <a target="_blank" class="ww-inline ww-online" title="点此可以直接和卖家交流选好的宝贝，或相互交流网购体验，还支持语音视频噢。" data-to-uid="{{sellerId}}">\n' +
            '                                                                <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>\n' +
            '                                                            </a>\n' +
            '                                                        </span>\n' +
            '                                                    </div>\n' +
            '                                                    <div class="fav-shop-box">\n' +
            '                                                        <div class="fshop-info-others-f floatleft">\n' +
            '                                                            <a class="J_TDialogTrigger">\n' +
            '                                                                <span class="iconfont icon-empty-star"></span>\n' +
            '                                                                <span class="J_FIconFace_Txt">收藏店铺</span>\n' +
            '                                                            </a>\n' +
            '                                                        </div>\n' +
            '                                                    </div>\n' +
            '                                                    <div class="shop-tools">\n' +
            '                                                        <ul class="shop-tools-list clearfix">\n' +
            '                                                            <li class="shop-tools-item shop-tools-item-del J_DeleteItem" title="删除">\n' +
            '                                                                <i class="iconfont icon-lajitong ljt" style="color: grey; font-size: 20px;"></i>\n' +
            '                                                            </li>\n' +
            '                                                        </ul>\n' +
            '                                                    </div>\n' +
            '                                                </div>\n' +
            '                                            </div>\n' +
            '                                            <div class="J_ItemListBox item-list-box -select">\n' +
            '                                                <div class="item-list">\n' +
            '                                                    <ul class="item-list-ul clearfix" data-spm-anchor-id="a1z0k.7628869.0.i0.317237deMHOg1M">\n' +
            '                                                       '+
            '                                                    </ul>\n' +
            '                                                </div>\n' +
            '                                            </div>\n' +
            '                                            <div class="edit-pop">\n' +
            '                                                <div class="edit-pop-bg"></div>\n' +
            '                                                <div class="edit-pop-border"></div>\n' +
            '                                                <div class="edit-pop-btn J_Edit_Pop_Btn" data-spm-click="gostr=/tbscj;locaid=d3sel">\n' +
            '                                                    <i class="edit-icon"></i>\n' +
            '                                                </div>\n' +
            '                                            </div>\n' +
            '                                            <div class="shop-popup J_ClassInfo">\n' +
            '                                                <div class="shop-score clearfix">\n' +
            '                                                </div>\n' +
            '                                                <div class="infor-detail shop-dsr">\n' +
            '                                                </div>\n' +
            '                                                <div class="infor-collector">\n' +
            '                                                    收藏人气：0\n' +
            '                                                </div>\n' +
            '                                            </div>\n' +
            '                                               <div class="del-pop">  ' +
            '                                                 <div class="del-pop-bg"></div>   ' +
            '                                                   <div class="del-pop-box">    ' +
            '                                                        <div class="txt">确定删除？</div>      ' +
            '                                                           <div class="btns">        ' +
            '                                                               <div class="J_DeleteItem_Ok btn-ok">确定</div>     ' +
            '                                               <div class="J_DeleteItem_Close btn-close">取消</div>  ' +
            '      </div>   ' +
            ' </div>' +
            '</div>'
            '</li>';
        var html = '',
            dateStr = (new Date()).toLocaleString();


            for (var i = 0; i < count; i++) {
                // 如果加载长度跟数据长度一样，则停止
                if(counterArr[counterIndex] == buyShopData[1]){
                    break;
                }
                // 先循环并获取店铺级html
                var newHtml = exports.renderTemplate(template2, {
                    shopName: buyShopData[0][counterArr[counterIndex]][0]['product']['shop']['shopName'],
                    sellerName: buyShopData[0][counterArr[counterIndex]][0]['product']['shop']['seller']['sellerName'],
                    sellerId: buyShopData[0][counterArr[counterIndex]][0]['product']['shop']['seller']['id'],
                    brandId: buyShopData[0][counterArr[counterIndex]][0]['product']['shop']['id'],
                    shopHead: buyShopData[0][counterArr[counterIndex]][0]['product']['shop']['shopHead'],
                    date: dateStr
                });
                var $nowShopEl = $(newHtml);
                // 再循环商品
                var nowShop = buyShopData[0][counterArr[counterIndex]];
                for (let j = 0; j < nowShop.length; j++) {
                    var productImage = nowShop[j]['product']['productImages'][0]['imagePath'];
                    var productId = nowShop[j]['product']['id'];
                    $nowShopEl.find(".item-list-ul").append("<li class='item-box g-sl-r-item'>\n" +
                        "<div class='item'>\n" +
                        "<a tabindex='-1' target='_blank' href='/buy.htm?pid="+productId+"' title=''>\n" +
                        "<img class='item-img' src='"+productImage+"' alt=''>\n" +
                        "</a>\n" +
                        "</div>\n" +
                        "</li>");
                }
                html += $nowShopEl[0].outerHTML;
                counterArr[counterIndex]++;
            }

        var child = exports.parseHtml(html);

        dom.appendChild(child);
    };

    /**
     * 绑定监听事件 暂时先用click
     * @param {String} dom 单个dom,或者selector
     * @param {Function} callback 回调函数
     * @param {String} eventName 事件名
     */
    exports.bindEvent = function(dom, callback, eventName) {
        eventName = eventName || 'click';
        if (typeof dom === 'string') {
            // 选择
            dom = document.querySelectorAll(dom);
        }
        if (!dom) {
            return;
        }
        if (dom.length > 0) {
            for (var i = 0, len = dom.length; i < len; i++) {
                dom[i].addEventListener(eventName, callback);
            }
        } else {
            dom.addEventListener(eventName, callback);
        }
    };
})(window.Common = {});
